import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { CronExpression, Cron } from '@nestjs/schedule';
import dayjs from 'dayjs';

import { CronOnce } from '~/common/decorators/cron-once.decorator';
import { ConfigKeyPaths } from '~/config';

@Injectable()
export class CronService implements OnApplicationBootstrap {
  private logger: Logger = new Logger(CronService.name);
  constructor(private readonly configService: ConfigService<ConfigKeyPaths>) {}

  // init任务 服务启动或重启时会执行一次
  async onApplicationBootstrap() {
    this.logger.debug(dayjs().format('YYYY-MM-DD HH:mm') + ' 定时任务-初始化');
  }

  @CronOnce(CronExpression.EVERY_DAY_AT_MIDNIGHT)
  handleCronOnce() {
    this.logger.debug(
      dayjs().format('YYYY-MM-DD HH:mm:ss') + ' 只执行一次的任务',
    );
  }

  // @Cron(CronExpression.EVERY_SECOND) // 每1秒钟执行一次
  // handleCron() {
  //   this.logger.debug(
  //     dayjs().format('YYYY-MM-DD HH:mm:ss') + ' 每秒执行的任务',
  //   );
  // }
}
